import os.path

from Module.xRayDetection.ftp_tree import *
from Module.xRayDetection.loacl_tree import TreeViewDemo
from Module.xRayDetection.config_utils import ConfigUtils
from mylibs.lib import *
from loguru import logger
from universal.root_path import *
from universal.txt_WR import txtwr
from universal.custom.code_widget import codeWidget
import xlrd
from Module.xRayDetection.extra_page import QComboCheckBox
from universal.widget_common import lineEdit_act,Table_widget,lineEdit_act_file,\
    lineEdit_act_s,SetCellWidget,Table_widget_setItem,lineEdit_act_files
from Module.xRayDetection.xray.xray import get_lines
from Module.xRayDetection.ExcelUtilsp import ExcelUtils
from universal.commom_widget.commonWidgetFunction import ButtonColor,Button
from universal.custom.ini_file import ODvision_config,ODModule_config,ODCode_setting,\
                        ODCode_config,ODCode_sections
from universal.commom_widget.Tablewidget import Tablewidget,Mainwindow_Label_table
from PyQt5.QtWidgets import *
__appname__ = '章鱼博士'

class MainWindow_FTP(QWidget):
    def __init__(self):
        super(MainWindow_FTP,self).__init__()
        #self.setWindowFlags(Qt.FramelessWindowHint)  # 无边框化
        self.init_widget()

    def init_widget(self):
        self.layout = QHBoxLayout(self)       #整体横向布局
        #--------------左侧界面&布局-------------
        self.leftwidget = QWidget()
        self.leftlayout = QVBoxLayout(self.leftwidget)
        #-------------browser----------------
        self.Path_Current = QLineEdit()
        self.TextBrowser = QTextBrowser(self)
        self.TextBrowser.setLineWrapMode(self.TextBrowser.NoWrap)
        self.TextBrowser.document().setMaximumBlockCount(100)
        self.TextBrowser.setMaximumHeight(100)
        self.TextBrowser.append('-------------消息栏--------------')
        #-----------------左下界面&布局--------------
        self.LeftDownWidget = QWidget()
        self.LeftDownWidget.setContentsMargins(0,0,0,0)
        self.LeftDownWidget.setMinimumHeight(490)
        self.LeftDownWidget_Layout = QVBoxLayout(self.LeftDownWidget)

        self.tree_ = TreeWidgetDemo(parent=self)
        self.tree_.tree.doubleClicked.connect(lambda: self.tree_.onTreeClicked(None))
        self.tree_.message = self.TextBrowser
        #----------------堆叠Tree------------
        self.stackedWidget = QStackedWidget()
        self.loaclTree = TreeViewDemo()
        self.stackedWidget.addWidget(self.tree_)
        self.stackedWidget.addWidget(self.loaclTree)
        #------------------------------------
        self.LeftDownWidget_Layout.addWidget(self.stackedWidget)
        # ----左侧布局添加----
        self.pageS_ = Demo(self)
        self.pageS_.setContentsMargins(0,0,0,0)#导入外部属性页


        self.leftlayout.addWidget(self.pageS_,Qt.AlignTop)
        self.leftlayout.addWidget(self.TextBrowser)
        self.leftlayout.addWidget(self.Path_Current)
        self.leftlayout.addWidget(self.LeftDownWidget)
        # ----整体布局添加----
        # self.layout.addWidget(self.leftwidget)
        self.tree_.Path_Current = self.Path_Current
        self.loaclTree.Path_Current = self.Path_Current
        #
        self.canvas = Canvas(parent=self)
        self.tree_.canvas = self.canvas
        self.loaclTree.canvas = self.canvas

        self.scrollArea = QScrollArea(self)
        self.scrollArea.setWidget(self.canvas)
        self.scrollArea.setWidgetResizable(True)
        self.scrollBars = {
            Qt.Vertical: self.scrollArea.verticalScrollBar(),
            Qt.Horizontal: self.scrollArea.horizontalScrollBar()
        }
        self.tree_.scrollArea = self.scrollArea
        self.tree_.scrollBars = self.scrollBars

        self.canvas.zoomRequest.connect(self.tree_.zoomRequest)
        self.canvas.scrollRequest.connect(self.scrollRequest)

        self.stack2 = QStackedLayout(self)  # 页面
        self.stack2.addWidget(self.canvas)
        self.scrollArea.setLayout(self.stack2)
        self.tree_.zoomWidget.valueChanged.connect(self.tree_.paintCanvas)
        self.layout.addWidget(self.scrollArea)


    def scrollRequest(self, delta, orientation):

        units = - delta / (8 * 15)
        bar = self.scrollBars[orientation]
        bar.setValue(bar.value() + bar.singleStep() * units)

    def StopDetect(self):
        self.tree_.main_detect.put({'stop': True})
        self.loaclTree.main_detect.put({'stop': True})

class Demo(QTabWidget):
    my_signal = pyqtSignal(object,str)
    def __init__(self, parent=None):
        super(Demo, self).__init__(parent=parent)
        self.MainFTP = parent
        self.setMinimumHeight(230)
        self.logs_ = init_log()
        self.Init_Widget()
        self.Module_Tab()
        self.logPath = dir_root() + os.sep + "Logs"
        # logger.add(self.logPath + os.sep + 'runtime_{time}.log', rotation="500 MB")
        logger.add(self.logPath + os.sep + 'export.log', rotation="500 MB")
        self.codeWidgetFtp = codeWidget('ftp')  #退出界面
        self.codeWidgetFtp.exit_FtpUpload.connect(self.PassWord_stop)

    def Init_Widget(self):
        self.Ftp = None
        self.Input_Path_S = None
        self.Upload_Path_4_Ftp = None
        self.Download_Path_5_Ftp = None
        self.Download_Path_5_Point = None
        self.name_list = []
        self.tree__ = self.MainFTP.tree_
        self.loca_tree__ = self.MainFTP.loaclTree
        self.stackedWidget_ = self.MainFTP.stackedWidget
        self.TextBrowser = self.MainFTP.TextBrowser
        self.my_signal.connect(TextBrowserNews)

    def Module_Tab(self):
        self.tab1UI()
        self.addTab(self.login_tableWidget, "登录")

        if ODModule_config.read_value('FTP', 'Tab2') == "1":
            self.tab2UI()
            self.Init_Tab2()
            self.addTab(self.detect_tableWidget, "检测")
        if ODModule_config.read_value('FTP', 'Tab3') == "1":
            self.tab3UI()
            self.Init_Tab3()
            self.addTab(self.export_tableWidget, "导出")
        if ODModule_config.read_value('FTP', 'Tab4') == "1":
            self.tab4UI()
            self.Init_Tab4()
            self.addTab(self.upload_tableWidget, "上传")
        if ODModule_config.read_value('FTP', 'Tab5') == "1":
            self.tab5UI()
            self.Init_Tab5()
            self.addTab(self.download_tableWidget, "下载")

    def tab1UI(self):
        self.login_tableWidget = Table_widget(self, 4, 2)
        name_list = ["本地端&FTP端", "主机", "用户名", "密码"]
        Table_widget_setItem(self.login_tableWidget, name_list)

        self.select_place = QComboBox()  # 本地或者FTP
        self.select_place.addItem("FTP端")
        self.select_place.addItem("本地端")
        self.select_place.currentIndexChanged[int].connect(self.on_cbBox_currentIndexChanged)
        self.hostLineEdit = QComboBox(self)
        self.hostLineEdit.setEditable(True)
        self.combobox_1 = QComboBox(self)
        self.combobox_1.setEditable(True)
        self.combobox_1.currentTextChanged.connect(lambda: self.on_combobox_func())  # 6
        self.codeLineEdit = QLineEdit('')
        self.codeLineEdit.setEchoMode(QLineEdit.Password)

        Host_ = ODCode_config.cfg.items("hostlist")
        for Host_name in Host_:
            name = Host_name[1]
            self.hostLineEdit.addItem(name)

        if len(ODCode_sections) != 0:
            for i in ODCode_sections:
                code_ = ODCode_config.read_value(i, 'name')
                if code_!='':
                    self.combobox_1.addItem(code_)

        self.hostLineEdit.setCurrentText(ODCode_config.read_value("current_ftp", 'currenthost'))
        self.combobox_1.setCurrentText(ODCode_config.read_value("current_ftp", 'currentname'))
        self.codeLineEdit.setText(ODCode_config.read_value("current_ftp", 'currentcode'))


        TabelParameter_Show_list = [self.select_place, self.hostLineEdit,
                                    self.combobox_1, self.codeLineEdit]
        SetCellWidget(self.login_tableWidget, TabelParameter_Show_list)

        self.loginButton = QPushButton('登录')
        self.loginButton.setStyleSheet(
            '''QPushButton{background:green;border-radius:5px;}QPushButton:hover{background:blue;}''')  # rgb(170,200,50)
        self.loginButton.clicked.connect(self.Login_Thread)

        self.login_tableWidget.insertRow(4)
        self.login_tableWidget.setSpan(4,0,1,2)  #合并的行数；列数；需要合并几行；几列
        self.login_tableWidget.setCellWidget(4, 0, self.loginButton)


    def tab2UI(self):
        self.detect_tableWidget = Tablewidget(14,2)
        name_list = ["本地储存路径", "FTP储存路径", "FTP检测路径", "FTP检测中间节点","FTP检测:","产线","设备","模型存放路径",
                     "conf_thres", "conf_model","cls_thres","cls_model","roi_thres","roi_model"]
        self.detect_tableWidget.Tablewidget_setItem(name_list)

        Table_widget_setItem(self.detect_tableWidget, name_list)
        self.DetectLocalSavePath = lineEdit_act_s(self)   #"本地结果储存路径"
        self.DetectFtpSavePath  = QLineEdit()  #FTP结果储存路径
        self.FtpDetectPath = QLineEdit() #FTP检测路径
        self.FtpDetectPath.setPlaceholderText('如果需要检测多个路径,路径之间用","隔开')

        self.FtpDetectPoint = QLineEdit()    #FTP检测中间节点
        self.FtpDetectPoint.setPlaceholderText('节点之间用","隔开')

        self.select_line = QComboBox()  #产线
        line_list = get_lines()
        for i in line_list:
            self.select_line.addItem(i)

        self.FtpDetectButton = Button('开始检测', lambda: self.ButtonStart('检测'))
        self.combox = QComboCheckBox() #设备
        self.LocalModelPath = lineEdit_act(self) #本地模型存放路径

        # - self.SavePath_---------------------------------------------
        self.conf_thres_line = QLineEdit("0.5")
        self.conf_thres_model = lineEdit_act_files(self, "Pt files (*.pt)")
        self.cls_thres_line = QLineEdit("0.5")
        self.cls_thres_model = lineEdit_act_files(self, "Pt files (*.pt)")
        self.roi_thres_line = QLineEdit("0.5")
        self.roi_thres_model = lineEdit_act_files(self, "Pt files (*.pt)")

        self.continues_detect = QCheckBox('开启连续检测')
        self.continues_detect.setChecked(True)
        self.detect_tableWidget.insertTablewidget(14, self.continues_detect)

        self.save_local_img = QCheckBox('检测图像保存至本地')
        self.save_local_xml = QCheckBox('检测xml保存至本地')
        self.save_remote_img = QCheckBox('检测图像保存至FTP')
        self.save_remote_xml = QCheckBox('检测xml保存至FTP')
        self.save_local_img.setChecked(True)
        self.save_local_xml.setChecked(True)
        self.save_remote_img.setChecked(True)
        self.save_remote_xml.setChecked(True)
        widget = QWidget()
        layout = QHBoxLayout()
        layout.addWidget(self.save_local_img)
        self.save_local_img.setStyleSheet("""height :100px""")
        layout.addWidget(self.save_local_xml)
        layout.addWidget(self.save_remote_img)
        layout.addWidget(self.save_remote_xml)
        widget.setMinimumHeight(25)
        widget.setLayout(layout)
        self.detect_tableWidget.insertTablewidget(15, widget)
        self.detect_tableWidget.setRowHeight(15,50)


        TabelParameter_Show_list = [self.DetectLocalSavePath, self.DetectFtpSavePath,self.FtpDetectPath,self.FtpDetectPoint,
        self.FtpDetectButton,self.select_line,self.combox,self.LocalModelPath,self.conf_thres_line,
        self.conf_thres_model,self.cls_thres_line,self.cls_thres_model,self.roi_thres_line,self.roi_thres_model]
        self.detect_tableWidget.SetCellWidget(TabelParameter_Show_list)



    def tab3UI(self):  #导出界面
        self.export_tableWidget = Table_widget(self,6,2)
        name_list = ["加载极组文件", "输入图像路径", "查询储存路径", "导出&停止:", "需要导出极组数", "总共导出极组数"]
        Table_widget_setItem(self.export_tableWidget, name_list)

        self.File_Edit_S = lineEdit_act_file(self,"Excel files (*.xlsx *.xls *.txt)")
        self.Input_Path_S = lineEdit_act(self)
        self.Save_Path_S = lineEdit_act(self)
        self.Need_num_s = QLineEdit()
        self.Need_num_s.setReadOnly(True)
        self.Already = QLineEdit()
        self.Already.setReadOnly(True)
        self.Start_Button_S = QPushButton('开始导出')
        self.Start_Button_S.setStyleSheet(
            '''QPushButton{background:green;border-radius:5px;}QPushButton:hover{background:blue;}''')
        self.Start_Button_S.clicked.connect(lambda: self.ButtonStart('导出'))

        self.export_tableWidget.insertRow(6)
        self.Start_Excel_S = QPushButton('Strat')
        self.Start_Excel_S.setStyleSheet(
            '''QPushButton{background:rgb(215,100,70);border-radius:5px;}QPushButton:hover{background:blue;}''')
        self.export_tableWidget.setCellWidget(6, 0, self.Start_Excel_S)
        self.Start_Excel_S.clicked.connect(self.exportExcelstart)
        self.ExportExcelLineEdit = lineEdit_act(self)
        self.export_tableWidget.setCellWidget(6, 1, self.ExportExcelLineEdit)

        TabelParameter_Show_list = [self.File_Edit_S, self.Input_Path_S, self.Save_Path_S,
                                    self.Start_Button_S, self.Need_num_s, self.Already]
        SetCellWidget(self.export_tableWidget, TabelParameter_Show_list)


    def tab4UI(self):
        self.upload_tableWidget = Table_widget(self, 7, 2)
        name_list = ["本地上传路径",'中间节点路径','Ftp上传存储路径',"FTP上传:","屏蔽路径关键词",'连续上传间隔/秒', '磁盘最大占用/％']
        Table_widget_setItem(self.upload_tableWidget, name_list)
        self.Upload_Path_4_Local = lineEdit_act_s(self)
        self.Upload_Path_4_Point = lineEdit_act_s(self)
        self.Upload_Path_4_Ftp = QLineEdit(self)
        self.isSecond = QSpinBox()
        self.isSecond.setRange(0, 999999)
        self.isSecond.setSingleStep(1)


        self.percent_upload = QSpinBox()
        self.percent_upload.setValue(50)
        self.percent_upload.setRange(1, 100)
        self.percent_upload.setSingleStep(1)

        self.BanPathWord_upload = QLineEdit()

        self.isContinuous = QCheckBox('开启连续上传')
        self.isContinuous.setChecked(True)
        self.Upload_Button_4 = QPushButton('开始上传')
        self.Upload_Button_4.clicked.connect(lambda: self.ButtonStart('上传'))
        self.Upload_Button_4.setStyleSheet(
            '''QPushButton{background:green;border-radius:5px;}QPushButton:hover{background:blue;}''')
        self.AutoLoginBox = QCheckBox('开机自动上传')
        self.AutoLoginBox.stateChanged.connect(self.AutoStatus)
        self.check()

        TabelParameter_Show_list = [self.Upload_Path_4_Local, self.Upload_Path_4_Point, self.Upload_Path_4_Ftp,
          self.Upload_Button_4, self.BanPathWord_upload, self.isSecond,self.percent_upload]
        SetCellWidget(self.upload_tableWidget, TabelParameter_Show_list)
        self.upload_tableWidget.insertRow(7)
        self.upload_tableWidget.insertRow(8)
        self.upload_tableWidget.setSpan(7,0,1,2)  #合并的行数；列数；需要合并几行；几列
        self.upload_tableWidget.setSpan(8,0,1,2)
        self.upload_tableWidget.setCellWidget(7, 0, self.isContinuous)
        self.upload_tableWidget.setCellWidget(8, 0, self.AutoLoginBox)

    def tab5UI(self):
        self.download_tableWidget = Table_widget(self, 7, 2)
        name_list = ["本地储存路径", "中间节点路径", 'Ftp下载路径', "FTP下载:", "屏蔽路径关键词", '连续下载间隔/秒', '磁盘最大占用/％']
        Table_widget_setItem(self.download_tableWidget, name_list)
        self.Download_Path_5_Local = lineEdit_act_s(self)
        self.Download_Path_5_Point = QLineEdit(self)
        self.Download_Path_5_Ftp = QLineEdit(self)
        self.BanPathWord_download = QLineEdit()

        self.isSecond_download = QSpinBox()
        self.isSecond_download.setRange(0, 999999)
        self.isSecond_download.setSingleStep(1)

        self.percent_download = QSpinBox()
        self.percent_download.setRange(1, 100)
        self.percent_download.setSingleStep(1)

        self.isContinuous_download = QCheckBox('开启连续下载')
        self.isContinuous_download.setChecked(True)
        self.Download_Button_5 = QPushButton('开始下载')
        self.Download_Button_5.clicked.connect(lambda: self.ButtonStart('下载'))
        self.Download_Button_5.setStyleSheet(
            '''QPushButton{background:green;border-radius:5px;}QPushButton:hover{background:blue;}''')
        # self.AutoLoginBox = QCheckBox('开启自动登录')
        # self.AutoLoginBox.stateChanged.connect(self.AutoStatus)
        TabelParameter_Show_list = [self.Download_Path_5_Local, self.Download_Path_5_Point,self.Download_Path_5_Ftp,
                    self.Download_Button_5,self.BanPathWord_download,self.isSecond_download,self.percent_download]
        SetCellWidget(self.download_tableWidget, TabelParameter_Show_list)
        self.download_tableWidget.insertRow(7)
        self.download_tableWidget.setSpan(7, 0, 1, 2)  # 合并的行数；列数；需要合并几行；几列
        self.download_tableWidget.setCellWidget(7, 0, self.isContinuous_download)

    def Init_Tab2(self):
        self.main_detect = queue.Queue()
        self.ini_detect = 1
        self.ListDetectQt = [self.DetectLocalSavePath, self.DetectFtpSavePath, self.FtpDetectPath, self.LocalModelPath,
                             self.conf_thres_line, self.conf_thres_model, self.cls_thres_line, self.cls_thres_model,
                             self.roi_thres_line, self.roi_thres_model,self.FtpDetectPoint]

        self.ListDetectIni = ['local_save_path', 'ftp_save_path', 'ftp_detect_path', 'local_model_path', 'conf_thres',
                              'conf_model','cls_thres', 'cls_model', 'roi_thres', 'roi_model',"ftp_point_path"]

        for idx,Qline in enumerate(self.ListDetectQt):
            if Qline == self.conf_thres_line or Qline == self.cls_thres_line or Qline == self.roi_thres_line:
                Qline.setText(ODvision_config.read_value('ftpDetect', self.ListDetectIni[idx]) or '0.5')
            else:
                Qline.setText(ODvision_config.read_value('ftpDetect', self.ListDetectIni[idx]))

    def write_tab(self,QtList,ini_name,ini_list):
        for idx,Qline in enumerate(QtList):
            self.LoggerPath(Qline, ini_name, ini_list[idx])


    def Init_Tab3(self):  #导出界面参数
        self.main = queue.Queue()
        self.ini_ = 1
        self.xlsx_name = ""
        self.imgspath_ = ""
        self.exportpath_ = ""
        self.listTable = []
        self.listTable_yuan = []
        self.allPath_list = []

        self.xlsx_name = ODvision_config.read_value('settings', 'TxtPath')
        self.imgspath_ = ODvision_config.read_value('settings', 'ExportPath')
        self.exportpath_ = ODvision_config.read_value('settings', 'ExportSavePath')
        self.File_Edit_S.setText(self.xlsx_name)
        self.Input_Path_S.setText(self.imgspath_)
        self.Save_Path_S.setText(self.exportpath_)


    def Init_Tab4(self):  # 上传界面参数
        self.ini_upload = 1
        self.main_upload = queue.Queue()
        self.ListUploadQt = [self.Upload_Path_4_Local, self.Upload_Path_4_Point, self.Upload_Path_4_Ftp, self.isSecond, self.percent_upload]
        self.ListUploadIni = ['uploadPath', 'pointPath', 'ftpSavePath', 'upload_time', 'percent_upload']

        for idx,Qline in enumerate(self.ListUploadQt):
            if Qline == self.isSecond or Qline == self.percent_upload:
                Qline.setValue(int(ODvision_config.read_value('ftpUpload', self.ListUploadIni[idx])))
            else:
                Qline.setText(ODvision_config.read_value('ftpUpload', self.ListUploadIni[idx]))

    def Init_Tab5(self):  # 下载界面参数
        self.ini_download = 1
        self.main_download = queue.Queue()

        self.ListDownloadQt = [self.Download_Path_5_Local,self.Download_Path_5_Point,self.Download_Path_5_Ftp,self.isSecond_download,self.percent_download]
        self.ListDownloadIni = ["localsavePath","pointpath","ftpDownloadPath","Download_time","percent_Download"]

        for idx,Qline in enumerate(self.ListDownloadQt):
            if Qline == self.isSecond_download or Qline == self.percent_download:
                Qline.setValue(int(ODvision_config.read_value('ftpDownload', self.ListDownloadIni[idx])))
            else:
                Qline.setText(ODvision_config.read_value('ftpDownload', self.ListDownloadIni[idx]))

    def ButtonStart(self,class_):
        if self.Ftp == None or "Goodbye" in self.Ftp.resp:
            TextBrowserNews(self.TextBrowser, '还未登录FTP!')
            return
        if class_ == '检测':
            self.tab2_detect_check_path()
        if class_ == '导出':
            self.tab3_daochu_check_path()
        if class_ == '上传':
            self.Type = 'Upload'
            self.Tab4_Upload_function()
        if class_ == '下载':
            self.Type = 'Download'
            self.Tab5_Download_function()

    #-------------------------------------- Tab2---Detect----------------------------
    def tab2_detect_start(self):
        self.TextBrowser.clear()
        if self.Ftp == None or "Goodbye" in self.Ftp.resp:
            TextBrowserNews(self.TextBrowser,'还未登录FTP!')
            return

    def tab2_detect_check_path(self):
        if self.ini_detect == 0:
            TextBrowserNews(self.TextBrowser, news='State:检测停止!')
            ButtonColor(self.FtpDetectButton, '开始检测')
            self.ini_detect = 1
            self.main_detect.put({'stop': True})
            return
        else:
            self.TextBrowser.clear()
            self.img_np = np.random.rand(10)
            self.connect_news = ''

            kwargs,sub_detect = self.tab2_detect_parameter()
            self.write_tab(self.ListDetectQt,'ftpDetect', self.ListDetectIni)
            FtpDetectPath = self.FtpDetectPath.text().split(",")  #判断是否要开启多个线程
            Point = self.FtpDetectPoint.text().split(",") #中间节点
            LocalSave = self.DetectLocalSavePath.text().split(",")  # "本地结果储存路径"
            FtpSave = self.DetectFtpSavePath.text().split(",") # "FTP结果储存路径"
            conf_thres_model = self.conf_thres_model.text().split(",")
            cls_thres_model = self.cls_thres_model.text().split(",")
            roi_thres_model = self.roi_thres_model.text().split(",")

            for idx,path_ in enumerate(FtpDetectPath):
                kwargs["remote_dir"] = path_
                kwargs["folder"] = Point[idx]

                kwargs["save_dir"] = LocalSave[idx]
                kwargs["upload_dir"] = FtpSave[idx]
                kwargs["fold_weights"] = conf_thres_model[idx]
                kwargs["cls_weights"] = cls_thres_model[idx]
                kwargs["roi_weights"] = roi_thres_model[idx]

                threading.Thread(target=run, kwargs=kwargs).start()


            self.ini_detect = 0
            self.PreProcess(self.main_detect, 'State:检测开始!', '停止检测', self.FtpDetectButton)
            kwargsVal = {'main': self.main_detect,
                      "sub": sub_detect,
                      "detect" : True}
            self.StatusThread = threading.Thread(target=self.GetVal_Log, kwargs=kwargsVal)
            self.StatusThread.daemon = True
            self.StatusThread.start()

    def tab2_detect_parameter(self):
        self.main_detect.queue.clear()
        sub_detect = queue.Queue()
        DeviceAll = self.combox.currentText()  # 选择设备
        if "c" in DeviceAll or 'C' in DeviceAll:
            device = 'cpu'
        else:
            device_list = re.findall(r"\d+\.?\d*", DeviceAll)
            device = str(",".join(device_list))

        host = self.host_
        host = host.replace('ftp://', '')
        host = host.replace('/', '')

        kwargs = {
            'logger': init_log(),
            'host': host,
            'line': self.select_line.currentText(),

            'fold_thres': self.conf_thres_line.text(),
            'cls_thres': self.cls_thres_line.text(),
            'roi_thres': self.roi_thres_line.text(),
            'device': device,

            'local_img': True if self.save_local_img.isChecked() else False,
            'local_xml': True if self.save_local_xml.isChecked() else False,
            'remote_img': True if self.save_remote_img.isChecked() else False,
            'remote_xml': True if self.save_remote_xml.isChecked() else False,

            # "crop" :
            # "split" :
            # ""

            "roi_weights": self.roi_thres_model.text(),
            "fold_weights": self.conf_thres_model.text(),
            "cls_weights": self.cls_thres_model.text(),

            "local_model_dir": self.LocalModelPath.text(),
            'save_dir': self.DetectLocalSavePath.text(),
            'remote_dir': self.FtpDetectPath.text(),
            'folder': self.FtpDetectPoint.text(),
            'remote_model_dir': '/platform/models',
            'upload_dir': None if self.DetectFtpSavePath.text() == '' else self.DetectFtpSavePath.text(),  # 必须传None，否则会上传至FTP
            'loop': True if self.continues_detect.isChecked() else False,  #是否停止
            'main_queue': self.main_detect,
            'sub_queue': sub_detect,
            'git_dir': os.path.join(dir_root(), 'DeepLearning', 'downloads')
        }
        return kwargs,sub_detect

    #-------------------------------------- Tab3---Daochu----------------------------
    def tab3_daochu_check_path(self):
        if self.ini_ == 0:
            TextBrowserNews(self.TextBrowser, news='State:导出停止!')
            ButtonColor(self.Start_Button_S, '开始导出')
            self.ini_ = 1
            self.main.put({'stop': True})
            return
        else:
            #——---------初始化路径-----------------
            self.number = 0
            self.tab3_daochu_excelpath()
            self.imgspath_ = self.LoggerPath(self.Input_Path_S, 'settings', 'ExportPath')
            self.exportpath_ = self.LoggerPath(self.Save_Path_S, 'settings', 'ExportSavePath')
            ODvision_config.write_value('settings', 'TxtPath', self.xlsx_name)
            if self.xlsx_name == "" or self.imgspath_ == "" or self.exportpath_ == "":
                TextBrowserNews(self.TextBrowser, 'Warning:请检查所有路径是否设置')
                return
            if not os.path.exists(self.exportpath_):  #
                os.makedirs(self.exportpath_)
            self.Already.setText(str(self.number))
            sub = self.PreProcess(self.main,'State:导出开始!','停止导出',self.Start_Button_S)
            self.ini_ = 0
            kwargs = {
                'items': self.imgspath_,
                'dir_': self.exportpath_,
                'main_queue': self.main,
                'sub_queue': sub,
                'codes': self.listTable,
                'remove': False,
            }
            self.ExportThread = threading.Thread(target=self.Ftp.find, kwargs=kwargs)#增加一个文件搜到是否删除另外文件相同条码
            self.ExportThread.daemon = True
            self.ExportThread.start()
            self.ExportValThread = threading.Thread(target=self.GetVal_Log, args=(self.main, sub, self.Start_Button_S))
            self.ExportValThread.daemon = True
            self.ExportValThread.start()

    # -------------------------------------- Tab4---Upload----------------------------
    def Tab4_Upload_function(self):
        if self.ini_upload == 0:
            self.IsOpenCode()
        else:
            # ——---------获取参数-----------------
            self.write_tab(self.ListUploadQt, 'ftpUpload', self.ListUploadIni) #写入ini文件

            loop = True if self.isContinuous.isChecked() else False
            if self.Upload_Path_4_Local.text() == "" or self.Upload_Path_4_Ftp.text() == "":
                TextBrowserNews(self.TextBrowser, '请检查上传路径是否设置!')
                return

            sub_upload = self.PreProcess(self.main_upload,'State:上传开始!','停止上传',self.Upload_Button_4)
            self.ini_upload = 0

            Secs = int(self.isSecond.text())
            Percent = float(self.percent_upload.text())/100
            LocalPath = self.Upload_Path_4_Local.text().split(",")  # 判断是否要开启多个线程
            Point = self.Upload_Path_4_Point.text().split(",")
            FtpPath = self.Upload_Path_4_Ftp.text().split(",")
            for idx, path_ in enumerate(LocalPath):
                kwargs = {
                    'items': path_,
                    'dir_': FtpPath[idx],
                    'main_queue': self.main_upload,
                    'sub_queue': sub_upload,
                    'folder': Point[idx],

                    'exclusions': [] if self.BanPathWord_upload.text().split(",")[0] == '' else self.BanPathWord_upload.text().split(","),
                    'loop': loop,
                    "secs": Secs,
                    'percentage': Percent
                }
                threading.Thread(target=self.Ftp.upload, kwargs=kwargs).start()

            GetValThread = threading.Thread(target=self.GetVal_Log, args=(self.main_upload, sub_upload,self.Upload_Button_4, loop, 'Upload'))
            GetValThread.daemon = True
            GetValThread.start()

    # -------------------------------------- Tab5---Download----------------------------
    def Tab5_Download_function(self):
        if self.ini_download == 0:
            self.IsOpenCode()
        else:
            # ——---------初始化路径-----------------
            self.write_tab(self.ListDownloadQt, 'ftpDownload', self.ListDownloadIni) #写入ini文件

            loop = True if self.isContinuous_download.isChecked() else False
            if self.Download_Path_5_Local. text() == "" or self.Download_Path_5_Ftp.text() == "":
                TextBrowserNews(self.TextBrowser, '请检查下载路径是否设置!')
                return
            sub_download = self.PreProcess(self.main_download,'State:下载开始!','停止下载',self.Download_Button_5)
            self.ini_download = 0

            Secs = int(self.isSecond_download.text())
            Percent = float(self.percent_download.text())/100
            LocalPath = self.Download_Path_5_Local.text().split(",")  # 判断是否要开启多个线程
            Point = self.Download_Path_5_Point.text().split(",")
            FtpPath = self.Download_Path_5_Ftp.text().split(",")
            for idx, path_ in enumerate(LocalPath):
                MK_dir(path_)

                kwargs = {
                    'items': FtpPath[idx],
                    'dir_': path_,
                    'main_queue': self.main_download,
                    'sub_queue': sub_download,
                    'folder': Point[idx],

                    'exclusions':  [] if self.BanPathWord_download.text().split(",")[0] == '' else self.BanPathWord_download.text().split(","),
                    'loop': loop,
                    "secs": Secs,
                    'percentage': Percent
                }
                threading.Thread(target=self.Ftp.download, kwargs=kwargs).start()

            GetValThread = threading.Thread(target=self.GetVal_Log, args=(self.main_download, sub_download, self.Download_Button_5, loop, 'Download'))
            GetValThread.daemon = True
            GetValThread.start()

    def GetVal_Log(self, main=None, sub=None, button=None, loop=False, Type='daochu', detect=False):
        while True:
            time.sleep(0.01)
            try:
                flags = main.get(block=False)
            except:
                flags = {}
            if flags.get('stop', False):
                main.put({'stop': True})
                break
            try:
                result = sub.get(block=False)
                if detect:    #检测
                    if result['idx'] == -1:
                        TextBrowserNews(self.TextBrowser, news='路径下没有文件')
                        ButtonColor(self.FtpDetectButton, '开始检测')
                        main.put({'stop': True})
                        break
                    if result['idx'] == result['total']:
                        self.ini_detect = 1
                        connect_ = result['msg']
                        ButtonColor(self.FtpDetectButton, '开始检测')
                        TextBrowserNews(self.TextBrowser, news=connect_)
                        TextBrowserNews(self.TextBrowser, news='检测完成')
                        break
                    if int(result['idx']) == 0:
                        self.TextBrowser.append(result['path'])
                    else:
                        connect_ = "第%s/%s ——>%s" % (result['idx'], result['total'], result['msg'])
                        if self.connect_news != connect_:
                            self.my_signal.emit(self.TextBrowser, connect_)
                            self.connect_news = connect_


                        if result['det'] != None:
                            if result['im'].all != self.img_np.all :
                                def picture():
                                    Img = self.tree__.drawDetectBox(result['im'], result['det'])
                                    Img = cvimg_to_qtimg(Img)
                                    self.tree__.loadImg(Img)
                                    self.img_np = result['im']
                                picture_start = threading.Thread(target=picture, args='')
                                picture_start.daemon = True
                                picture_start.start()

                else:     #导出,上传,下载
                    if result['msg'] == None:
                        TextBrowserNews(self.TextBrowser, news='运行结束！')
                        if Type == 'daochu':
                            self.ini_ = self.setIni(button,"开始导出")
                        if Type == 'Upload':
                            self.ini_upload = self.setIni(button, "开始上传")
                        if Type == 'Download':
                            self.ini_download = self.setIni(button, "开始下载")
                        if loop == False:
                            break
                    else:
                        self.my_signal.emit(self.TextBrowser,result['msg'])
                        if Type == 'daochu':
                            result['codes'] = list(set(result['codes']))
                            self.SAVE_TXT(result['codes'])
                            self.number = len(result['codes'])
                            self.Already.setText(str(self.number))
                        if self.number == len(self.listTable):
                            self.ini_ = 1
                            self.SAVE_TXT(result['codes'])
                            ButtonColor(self.Start_Button_S, '开始导出')
                            break

            except Exception as e:
                result = {}

    def IsOpenCode(self):
        if ODModule_config.read_value('OpenCode', 'page') == "1":
            self.codeWidgetFtp.show()
            self.codeWidgetFtp.clearLine()
        else:
            self.PassWord_stop()

    def SAVE_TXT(self, jizu):
        PosetiveEscapetxt = self.exportpath_ + os.sep + "name" + '.txt'
        wr_txt = txtwr(PosetiveEscapetxt)
        wr_txt.write(jizu)

    def setIni(self,button,news):
        ButtonColor(button,news)
        button.setEnabled(True)
        return 1

    def PreProcess(self,mainQueue,news,news2,button):
        sub = queue.Queue()
        mainQueue.queue.clear()
        self.TextBrowser.clear()
        TextBrowserNews(self.TextBrowser, news=news)
        button.setText(news2)
        button.setStyleSheet(
            '''QPushButton{background:rgb(255,0,0);border-radius:5px;}QPushButton:hover{background:blue;}''')
        return sub

    def IfExistsPath(self,path,news):
        if not os.path.exists(path):  #
            TextBrowserNews(self.TextBrowser, news=news)
            return False
        else:
            return True

    def LoggerPath(self,LineText,config1,config2):
        name = self.Logger_Path(LineText.text())
        ODvision_config.write_value(config1, config2, name)
        return name

    def AutoStatus(self):
        try:
            from universal.custom.TestRun import check
            if self.AutoLoginBox.isChecked():
                ODvision_config.write_value('settings', 'autologin', '1')
                check(state=1)
            else:
                ODvision_config.write_value('settings', 'autologin', '0')
                check(state=0)
        except Exception as e:
            print(str(e))
            TextBrowserNews(self.TextBrowser, news=str(e))

    def check(self):
        if ODvision_config.read_value('settings', 'autologin') == "1":
            self.AutoLoginBox.setChecked(True)
        else:
            self.AutoLoginBox.setChecked(False)

    def Logger_Path(self, path):
        logger.info(path)
        return path

    def PassWord_stop(self):
        self.codeWidgetFtp.close()
        if self.Type == 'Upload':
            self.ini_upload = self.PassWord_stop_('State:上传停止!',self.Upload_Button_4,"开始上传",self.main_upload)
        if self.Type == 'Download':
            self.ini_download = self.PassWord_stop_('State:下载停止!',self.Download_Button_5,"开始下载",self.main_download)

    def PassWord_stop_(self,news1,button,news2,main_):
        TextBrowserNews(self.TextBrowser, news=news1)
        ButtonColor(button,news2)
        main_.put({'stop': True})
        return 1

    def tab3_daochu_excelpath(self):
        self.xlsx_name = self.File_Edit_S.text()
        logger.info(self.xlsx_name)
        self.listTable.clear()
        self.listTable_yuan.clear()
        self.File_Edit_S.setText(self.xlsx_name)
        self.Need_num_s.setText(str(len(self.listTable)))
        try:
            if self.xlsx_name != '':
                (file, ext) = os.path.splitext(self.xlsx_name)
                if ext != '.xlsx' and ext != '.xls' and ext != '.txt':
                    logger.info('load Excel is failed')
                    TextBrowserNews(self.TextBrowser, "提示:输入Excel路径后缀不是.xlsx/.xls/.txt")
                    return

                elif ext == '.xlsx' or ext == '.xls':
                    worksheet = xlrd.open_workbook(self.xlsx_name)
                    sheet = worksheet.sheet_by_index(0)
                    nrows = sheet.nrows  # 行数
                    ncols = sheet.ncols  # 列数
                    for i in range(1, nrows):
                        data = sheet.cell(i, 1).value
                        if data != '':
                            self.listTable.append(data)
                            self.listTable_yuan.append(data)
                    logger.info('load Excel is success')
                    TextBrowserNews(self.TextBrowser, "Excel加载成功")
                    return

                elif ext == '.txt':
                    f = open(self.xlsx_name, encoding="utf-8")
                    listOftxt = f.readlines()
                    for i in range(len(listOftxt)):
                        data = listOftxt[i]
                        data = data.split('\n')[0]
                        if data != '':
                            self.listTable.append(data)
                            self.listTable_yuan.append(data)
                    f.close()
                    self.Need_num_s.setText(str(len(self.listTable)))
                    logger.info('load txt is success')
                    TextBrowserNews(self.TextBrowser, "txt加载成功")
                    return
            else:
                return
        except Exception as e:
            self.listTable.clear()
            self.File_Edit_S.setText("")
            self.Need_num_s.setText(str(len(self.listTable)))
            print("except:", e)
            TextBrowserNews(self.TextBrowser, "Excel加载_wrong")
            return

    def exportExcelstart(self):
        self.TextBrowser.clear()
        self.allPath_list.clear()
        sub = queue.Queue()
        self.list_get = []

        self.exportExcelPath_0 = self.ExportExcelLineEdit.text()
        self.exportExcelPath_ = '/'.join(self.exportExcelPath_0.split('\\'))
        logger.info(self.exportExcelPath_)
        if self.exportExcelPath_ == '':
            self.TextBrowser.append('请选择导出目录路径!!!')
            return
        self.exportExcstart = threading.Thread(target=self.exportExcelstart_, args=(sub,))
        self.exportExcstart.daemon = True
        self.exportExcstart.start()

    def exportExcelstart_(self,sub):
        try:
            self.TextBrowser.append('导出启动')
            filename = self.exportExcelPath_ + os.sep + 'barcode.xls'
            self.allPath_list = get_img_list(self.exportExcelPath_, [], ext=['jpg', 'png', 'JPG'
                                                                            ,'jpeg', 'bmp','PNG',
                                                                                  'JPEG','BMP'])
            ExcelUtils.write_to_excel(self.allPath_list, filename, sub)
            self.TextBrowser.append('导出完成')
        except Exception as e:
            self.TextBrowser.append(str(e))

    def on_cbBox_currentIndexChanged(self, index):
        '''下拉框选择改变时 就改变 层叠窗口部件的当前页面'''
        #--------------------------
        self.stackedWidget_.setCurrentIndex(index)

    def on_combobox_func(self):
        name_ = self.combobox_1.currentText()
        for i in ODCode_sections:
            Host_name = ODCode_config.read_value(i, 'name')
            if name_ == Host_name:
                self.codeLineEdit.setText(ODCode_config.read_value(i, 'code'))

    def Login_Thread(self):
        # if self.ini_login == 0:
        #     TextBrowserNews(self.TextBrowser, news='State:退出FTP!')
        #     if self.Ftp != None:
        #         self.Ftp.close()
        #     self.tree__.tree.clear()
        #     self.loginButton.setText("登录")
        #     self.loginButton.setStyleSheet(
        #         '''QPushButton{background:rgb(0,125,0);border-radius:5px;}QPushButton:hover{background:blue;}''')
        #     self.ini_login = 1
        #     return
        # else:
        #     self.loginButton.setText('退出')
        #     self.loginButton.setStyleSheet(
        #         '''QPushButton{background:rgb(255,0,0);border-radius:5px;}QPushButton:hover{background:blue;}''')
        #     self.ini_login = 0
        self.TextBrowser.clear()
        self.name_list.clear()
        thread_login = threading.Thread(target=self.Login, args='')
        thread_login.daemon = True
        thread_login.start()

    def Login(self):
        self.loginButton.setEnabled(False)
        self.host_ = self.hostLineEdit.currentText()
        name_ = self.combobox_1.currentText()
        code_ = self.codeLineEdit.text()

        self.TextBrowser.append('正在连接中...')
        self.Ftp,host = Login2(self.host_,name_,code_,self.logs_)
        self.tree__.host = self.host_
        self.tree__.Ftp = self.Ftp
        self.tree__.tree.clear()
        self.TextBrowser.append(self.Ftp.resp)
        if "230" in self.Ftp.resp:
            gen = r'/'
            root = QTreeWidgetItem(self.tree__.tree)
            root.setText(0, gen)
            root.setIcon(0, QIcon(":icons/dir.png"))

            self.tree__.loginButton = self.loginButton
            self.tree__.Input_Path_S = self.Input_Path_S
            self.tree__.Upload_Path_4_Ftp = self.Upload_Path_4_Ftp
            self.tree__.Download_Path_5_Ftp = self.Download_Path_5_Ftp
            self.tree__.Download_Path_5_Point = self.Download_Path_5_Point

            self.tree__.onTreeClicked(root)

            #-----------------------
            if len(ODCode_sections) == 0:
                counter = "counter1"
                self.ini_process(counter, name_, code_)
            else:
                for i in ODCode_sections:
                    Host_name = ODCode_config.read_value(i, 'name')
                    self.name_list.append(Host_name)
                if name_ not in self.name_list:
                    title_name = "counter" + str(len(ODCode_sections) + 1)
                    self.ini_process(title_name, name_, code_)

                Host_List = []
                for i in ODCode_config.cfg.items("hostlist"):
                    Host_List.append(i[1])
                if self.host_ not in Host_List:
                    ODCode_config.write_value("hostlist", "host" + str(len(ODCode_config.cfg.items("hostlist"))),
                                              self.host_)

        else:
            self.Ftp = None
            self.loginButton.setEnabled(True)

        ODCode_config.write_value("current_ftp", 'currenthost', self.host_)
        ODCode_config.write_value("current_ftp", 'currentname', name_)
        ODCode_config.write_value("current_ftp", 'currentcode', code_)

    def ini_process(self, counter, name, code):
        ODCode_config.write_value(counter, 'name', name)
        ODCode_config.write_value(counter, 'code', code)
        self.combobox_1.addItem(name)

from threading import Thread
class PictureThreadQT(Thread):

    def __init__(self,result,tree,img):
        Thread.__init__(self)
        self.result = result
        self.tree = tree
        self.img = img
    def run(self):
        # Img = self.tree.drawDetectBox(self.result['im'], self.result['det'])
        # Img = cvimg_to_qtimg(Img)
        self.tree.loadImg(self.img)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    w = MainWindow_FTP()
    # w.showMaximized()
    w.show()
    sys.exit(app.exec())
